import md5 from "./md5.js"

export const wxPayment = (option) => {
    const options = {
        timeStamp: '',
        nonceStr: '',
        prepayid: '',
        paySign: '',
        ...option
    }
    return new Promise((resolve, reject) => {
        /*
  *
  string(301)
  "{"appId":"wx565a9a61bb43c148"
  * "nonceStr":"aml3xm3lbxxo4hi0ra5vocjux8007s9o",
  * "package":"Sign=WXPay",
  * "partnerId":"1616415552",
  * "prepayId":"wx1017241040712648a609f84d0445860000",
  * "signType":"HMAC-SHA256",
  * "timeStamp":"1665393850",
  * "paySign":"EF4D96C61785334D915EF82F4DFE0A2F71BF448C0AE48647B1296079581C5E02"}"
  *
  * ***/
        // #ifdef APP-PLUS
        /*
   * 生成指定的随机字符串
   * @params isRandomLength: boolean 是否在min ~ max生成随机长度
   * @params min: number 最小长度
   * @params max: number 最大长度
   */
        function randomSrt(isRandomLength, min, max) {
            let str = "",
                range = min;
            const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                'l',
                'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
                'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
            ];

            // 随机产生
            if (isRandomLength) {
                range = Math.round(Math.random() * (max - min)) + min;
            }
            for (var i = 0; i < range; i++) {
                let pos = Math.round(Math.random() * (arr.length - 1));
                str += arr[pos];
            }
            return str;
        }

        /*
         * 根据object生成key value字符串
         * @params obj: any 要map的对象
         * @params isSort: boolean 是否根据ASCII字典排序
         */
        function mapObjToKeyValue(obj, isSort = false) {
            let keys = Object.keys(obj);
            let str = "";
            if (isSort) keys.sort();
            keys.forEach(key => {
                if (obj.hasOwnProperty(key)) {
                    str += `${key}=${obj[key]}&`;
                }
            });
            return str.replace(/&$/, "");
        }

        function getPayInfo(orderInfo) {
            const res = orderInfo, // 统一下单返回数据
                time = new Date(),
                timestamp = time.getTime().toString().substr(0, 10), // 时间戳
                noncestr = randomSrt(true, 10, 20), // 随机数
                key = "AE0EB3D3E9F2D866FC2F021102B1A83A", // 加密Key，微信支付填写的key
                payInfo = {
                    appid: res.appId,
                    noncestr,
                    package: 'Sign=WXPay',
                    partnerid: res.partnerId,
                    prepayid: res.prepayId,
                    timestamp: Number(timestamp)
                }
            // 键值对按照ASCII码从小到大排序生成类似：appid=xxx&body=xx&device_info=1000
            let keyValueStr = mapObjToKeyValue(payInfo, true);

            // 插入加密Key到最后
            let strSignTemp = `${keyValueStr}&key=${key}`;
            // 真正的二次加密
            let sign = md5.hex_md5(strSignTemp).toUpperCase().substr(0, 32);
            // 可以去微信支付文档做校验
            payInfo.sign = sign;
            // 返回字符串给uniapp调起支付用
            return JSON.stringify(payInfo);
        }

        let orderInfo = getPayInfo(options);

        // let orderInfo = {
        // 	"appid":options.appId,
        // 	"noncestr": options.nonceStr,
        // 	"prepayid": options.prepayId,
        // 	"package": "Sign=WXPay",
        // 	"partnerid":options.partnerId,
        // 	"timestamp": options.timeStamp,
        // 	"sign":(options.paySign)
        // }
        uni.getProvider({
            service: 'payment',
            success: function (res) {
                console.log(res.provider)
                if (~res.provider.indexOf('wxpay')) {
                    uni.requestPayment({
                        "provider": "wxpay",  //固定值为"wxpay"
                        "orderInfo": orderInfo,
                        success: function (res) {
                            var rawdata = JSON.parse(res.rawdata);
                            console.log(rawdata + "支付成功");
                        },
                        fail: function (err) {
                            console.log('支付失败:' + JSON.stringify(err));
                        }
                    });
                }
            }
        });


        // let payObj = {
        // 	appid:"wxbf34f4f4a320dd42",
        // 	timeStamp:new Date().getTime(),
        // 	key:""
        // }
        // payObj.paySign = md5.hexMD5('appId=' + payObj.appid + '&nonceStr=' + res.data.data.nonce_str + '&package=' + res.data.data.prepay_id + '&signType=MD5&timeStamp=' + payObj.timeStamp + "&key=" + payObj.key).toUpperCase();
        // console.log(obj)
        // console.log(obj)
        // uni.requestPayment({
        //   provider: 'wxpay',
        // orderInfo: obj,
        //   success: res => resolve(res),
        //   fail: res => reject(res)
        // })


        // #endif
        // #ifdef MP-WEIXIN
        //小程序充值走这个
        uni.requestPayment({
            provider: 'wxpay',
            timeStamp: options.timeStamp,
            nonceStr: options.nonceStr,
            package: options.package,
            signType: options.signType,
            paySign: options.paySign,
            success: res => resolve(res),
            fail: res => reject(res)
        })
        // #endif
        // #ifdef H5
        function onBridgeReady() {
            // alert(objs.timestamp)
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', option,
                function (res) {
                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
        }

        if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady(), false);
            } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady());
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady());
            }
        } else {
            onBridgeReady();
        }
        // #endif
    })
}

export const zfbPayment = (option) => {

    return new Promise((resolve, reject) => {
		console.log(option)
        uni.requestPayment({
            provider: 'alipay',
            orderInfo: option,
            success: res => resolve(res),
            fail: res => reject(res)
        })
    })
}